<?php


namespace app\common\model;


use think\Model;
use traits\model\SoftDelete;

class UserBeansLog extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'user_beans_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    protected $dateFormat = 'Y-m-d H:i:s';

    // 定义时间戳字段名
    protected $createTime = 'create_dt';
    protected $updateTime = 'update_dt';
    protected $deleteTime = 'delete_dt';

    // 追加属性
    protected $append = [
        'log_type_text'
    ];


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function getList($userId, $page = 1, $extend = [], $pageSize = 20)
    {
        $start = ($page - 1) * $pageSize;
        $where = ['user_id' => $userId];
        $where = array_merge($where, $extend);
        $list = $this->where($where)->limit($start, $pageSize)->order("id", "desc")->select();
        $total = $this->where($where)->count();
        if (!$list) {
            $list = [];
        }
        if (!$total) {
            $total = 0;
        }
        return ['list'=>$list,'total'=>$total];
    }

    public function getLogTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['log_type']) ? $data['log_type'] : '');
        $list = [1 => '下单返豆', 2 => '提现', 3 => '返利', 4 => '提现驳回'];
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 添加金额变动记录
     * @param $userId int 商家ID
     * @param $logType int 变动类型:1=充值,2=发布商品,3=提现,4=冻结返还,5=下级返佣
     * @param $money     float 变动金额
     * @param $memo   string 变动说明
     * @param $extend     array 其他
     * @return UserMoneyLog
     */
    public static function addLog($userId, $logType, $money, $memo, $extend = [])
    {
        $data = [
            'user_id' => $userId,
            'log_type' => $logType,
            'beans' => $money,
            'log_desc' => $memo,
        ];
        $data = array_merge($data, $extend);
        return self::create($data);
    }


}